package de.homelabs.moonrat.security.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import de.homelabs.moonrat.page.MoonratPageManager;
import de.homelabs.moonrat.security.MoonratSecurityManager;
import de.homelabs.moonrat.util.MoonratWebUtils;

@Component
public class MoonratDomainFilter implements javax.servlet.Filter {

	static final Logger logger = Logger.getLogger(MoonratDomainFilter.class);
	
	@Autowired
	private MoonratPageManager mPageManager;
	
	@Autowired
	private MoonratSecurityManager mSecurityManager;
	
	/*
	 * (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		//no-op
	}

	/*
	 * (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		if (mSecurityManager.isDomainSupported(MoonratWebUtils.getDomainFromRequest(request))){
			//continue with filter chain
			filterChain.doFilter(request, response);
		} else {
			StringBuffer content = mPageManager.getFallbackTemplate(new StringBuffer("<h1>An error occured: </h1><p>Domain is not supported!</p>"));
			httpResponse.getWriter().print(content.toString());
			httpResponse.flushBuffer();
		}
	}

	/*
	 * (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		//no-op
	}
}
